package org.funtester.performance.books.chapter10.section3;

import org.apache.commons.pool2.impl.GenericKeyedObjectPool;
import org.apache.commons.pool2.impl.GenericKeyedObjectPoolConfig;
import org.funtester.performance.books.chapter09.section3.UserBehavior;

import java.time.Duration;

public class KeyedUserBehaviorPool {

    public static void main(String[] args) throws Exception {
        GenericKeyedObjectPool<String, UserBehavior> keyedUserBehaviorPool = initKeyedUserBehaviorPool();// 初始化对象池
        UserBehavior userBehavior = keyedUserBehaviorPool.borrowObject("login");// 从对象池中获取对象
        userBehavior.id = 1;// 设置用户id
        userBehavior.action = "login";// 设置用户行为
        userBehavior.content = "地点北京";// 设置用户行为内容
        userBehavior.timestamp = System.currentTimeMillis();// 设置用户行为时间戳
        System.out.println("第一次借出对象hashCode: " + userBehavior.hashCode());// 打印对象的hashcode
        System.out.println(userBehavior);// 打印对象内容
        keyedUserBehaviorPool.returnObject("login", userBehavior);// 归还对象
        UserBehavior userBehaviorSecond = keyedUserBehaviorPool.borrowObject("login");// 再次获取对象
        System.out.println("第二次借出对象hashCode: " + userBehaviorSecond.hashCode());// 打印对象的hashcode
        System.out.println(userBehaviorSecond);// 打印对象内容
        keyedUserBehaviorPool.close();// 关闭对象池
    }

    /**
     * 初始化keyedUserBehaviorPool对象池
     * @return
     */
    public static GenericKeyedObjectPool<String, UserBehavior> initKeyedUserBehaviorPool() {
        GenericKeyedObjectPoolConfig poolConfig = new GenericKeyedObjectPoolConfig<>();
        poolConfig.setMaxTotal(1000);// 设置最大对象数
        poolConfig.setMinIdlePerKey(10);// 设置每个子对象池最小空闲对象数
        poolConfig.setMaxIdlePerKey(500);// 设置每个子对象池最大空闲对象数
        poolConfig.setMaxWait(Duration.ofMillis(1000));// 设置最大等待时间
        poolConfig.setMinEvictableIdleTime(Duration.ofMillis(1000));// 设置最小空闲时间
        poolConfig.setBlockWhenExhausted(true);// 设置对象池耗尽时是否阻塞
        poolConfig.setTimeBetweenEvictionRuns(Duration.ofMillis(1000));// 设置回收时间间隔
        return new GenericKeyedObjectPool<String, UserBehavior>(new KeyedUserBehaviorFactory(), poolConfig);
    }

}
